//
//  CommentsViewController.swift
//  
//
//  Created by Ralf on 15/6/14.
//
//

import UIKit

class CommentsViewController: TableViewController
{
    var articleId: String!
    let commentManager = CommentManager()
    var comments       = NSMutableArray()
    var offset         = 0
    let max            = 10
    var end            = false
    let appDelegate    = UIApplication.sharedApplication().delegate as! AppDelegate
    let screen         = UIScreen.mainScreen().bounds

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.navigationItem.title = "全部评论"
        self.tableView.registerNib(UINib(nibName: "CommentsViewAvatarCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "AVATAR")
        self.tableView.registerNib(UINib(nibName: "CommentsViewCommentCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "COMMENT")
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        initBackButton()
//        initAddCommentButton()
    }

    func initAddCommentButton()
    {
        let button
        = UIBarButtonItem(image: UIImage(named: "Post-Small.png")!.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "addComment:")
        self.navigationItem.rightBarButtonItem = button
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return comments.count * 2
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let mode = indexPath.row % 2

        if mode <= 0
        {
            let cell    = tableView.dequeueReusableCellWithIdentifier("AVATAR", forIndexPath: indexPath) as! CommentsViewAvatarCell
            let index   = Int(indexPath.row / 2)
            let comment = comments[index] as! [String:AnyObject]
            cell.setData(comment)
            return cell
        }
        else
        {
            let cell    = tableView.dequeueReusableCellWithIdentifier("COMMENT", forIndexPath: indexPath) as! CommentsViewCommentCell
            let index   = Int(indexPath.row / 2)
            let comment = comments[index] as! [String:AnyObject]
            cell.setData(comment)
            return cell
        }
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        let i = indexPath.row % 2

        if i == 0
        {
            return 40.0
        }
        else
        {
            let comment = comments[indexPath.row / 2] as! NSDictionary
            let message = comment["message"] as! String
            let size    = sizeOfText(message)
            return size.height * 1.2 + 10
        }
    }

    func setData(data: String)
    {
        articleId = data

        loadData()
    }

    func loadData()
    {
        if end
        {
            return
        }

        let rs = commentManager.queryByArticleID(articleId, offset: offset, max: max)

        if rs == nil
        {
            alertNetworkConnectionException()
            return
        }

        if rs.isEmpty()
        {
            end = true
            return
        }

        comments.addObjectsFromArray(rs.toArray())

        offset = comments.count

        tableView.reloadData()
    }
    //
    //    func loadComments()
    //    {
    //        NSString* articleID;
    //
    //        if(article.count > 2)
    //        {
    //            articleID = article[@"id"];
    //        }
    //        else
    //        {
    //            articleID = article[@"article"][@"id"];
    //        }
    //        ResultSet* rs = [commentManager queryByArticleID:articleID];
    //
    //        if([self verifyResutSet:rs])
    //        {
    //            comments = [rs toArray];
    //        }
    //
    //        [self.tableView reloadData];
    //    }

    @IBAction func addComment(sender: AnyObject)
    {
        if appDelegate.isLogged()
        {
            let controller = CommentFormViewController()
            controller.articleId = articleId
            self.pushViewController(controller)
        }
        else
        {
            login()
        }
    }

    @IBAction override func reloadData(sender: AnyObject)
    {
        end = false
        offset = 0
        comments.removeAllObjects()
        loadData()
        super.reloadData(sender)
    }

    func sizeOfText(text: NSString) -> CGSize
    {
        let paragraphStyle = NSMutableParagraphStyle()

        paragraphStyle.lineHeightMultiple = 16
        paragraphStyle.maximumLineHeight = 16
        paragraphStyle.minimumLineHeight = 16

        //        paragraphStyle.firstLineHeadIndent = 20
        paragraphStyle.alignment = .Left

        let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(12),
                          NSParagraphStyleAttributeName: paragraphStyle,
                          NSForegroundColorAttributeName: UIColor.darkGrayColor()]


        let frame = CGSizeMake(screen.size.width - 50, screen.size.height)
        let options = unsafeBitCast(NSStringDrawingOptions.TruncatesLastVisibleLine.rawValue|NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue |
            NSStringDrawingOptions.UsesFontLeading.rawValue,
            NSStringDrawingOptions.self)
        let size  = text.boundingRectWithSize(frame, options: options, attributes: attributes, context: nil)
        return size.size
    }
}
